package uit.edu.vn.Activity;

//class music dung de load danh sach cac bai hat tu sdcard va dua vao list , 
//moi item cua list gom 1 imageview, 2 textview (ten bai hat , nhac sy),
//su dung thread de tach load nhac voi UI
import java.io.File;
import java.io.FileInputStream;

import java.util.ArrayList;

import uit.edu.vn.Model.myMusic;
import uit.edu.vn.Utility.AESControl;
import uit.edu.vn.Utility.CheckInternet;
import uit.edu.vn.Utility.MusicListAdapter;
import uit.edu.vn.Utility.MyActivity;
import uit.edu.vn.Utility.httpUploader;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.MediaStore.Audio;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;

public class MusicActivity extends MyActivity {
	private Cursor myCursor;
	
	private ListView listview;
	private Context context;
	private TextView titleHeader;
	private ProgressDialog loadingMusicDialog;
	private int numberOfItemSelected = 0;
	private MusicListAdapter mAdapter ;
	//private String urlString = "http://10.0.2.2:8080/ServerWeb/UploadServlet.jsp";
//	private String urlString = "http://"+ LoginActivity.getIPAddress()+"/ServerWeb/UploadServlet.jsp";
	private String urlString = null;
	private final ArrayList<myMusic> listMusic = new ArrayList<myMusic>(); 
    private ArrayList<myMusic> itemMusicCheck= new ArrayList<myMusic>();
    private String userid = "";
    private String username = "";
    private String password = "";
	private int filetype = 3;
	private Double maxSize=0.;
    private static final String STRING_NAME_USERSETTING = "USER REFERENCES";
    private SharedPreferences ShareRef = null;	
    private AESControl aes;
  
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);

        username = getSetting("username");
        password = getSetting("password");
        userid   = getSetting("userid");
        urlString = "http://"+ getSetting("address")+"/ServerWeb/UploadServlet.jsp";
        
		setContentView(R.layout.backup_file);
		//kiem tra neu username va password rong thi ket thuc activity hien tai va goi activity login
		if(username.equals("") && password.equals("")){
	          Intent intent = new Intent(MusicActivity.this, LoginActivity.class);
	          startActivity(intent);
	          this.finish();            	
	      }
		
        System.out.println("MusicActivity");
        System.out.println("username: "+ username);
        System.out.println("password: "+ password);
        System.out.println("userid:   "+ userid);
        System.out.println("address:   "+ urlString);
		
		
		listview =(ListView)findViewById(R.id.listFileBackup);
		listview.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
		titleHeader=(TextView)findViewById(R.id.txt_titleFile);
		titleHeader.setText(R.string.title_BackupHeaderMusic);
		context=getBaseContext();
		loadingMusicDialog= new ProgressDialog(this);
		loadingMusicDialog.setMessage(getResources().getString(R.string.dialog_message_progress));
		loadingMusicDialog.setCancelable(false);
		loadingMusicDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
		new BackGround().execute();
		listview.setOnCreateContextMenuListener(this);
		listview.setOnItemClickListener(new OnItemClickListener() 
	        {
	     	   @Override
	     	   public void onItemClick(AdapterView<?> arg0, View arg1, final int position,
	 			long arg3) {
	     		   
	     		   	try {
	     		   		showConfirmDialog(getResources().getString(R.string.dialog_thongbao),getResources().getString(R.string.dialog_message_mo), new OnClickListener() {
							
							@Override
							public void onClick(DialogInterface dialog, int which) 
							{
								// TODO Auto-generated method stub

								myMusic entry = listMusic.get(position);
			     		   		File temp = new File(entry.getPath());
			     		   		Intent myIntent= new Intent();
								myIntent.setAction(android.content.Intent.ACTION_VIEW);
								myIntent.setDataAndType(Uri.fromFile(temp), "audio/*") ;  
								startActivity(myIntent);
							}
						});
	     		   	} catch (Exception e) {
						// TODO: handle exception
						  e.printStackTrace();
					}
	     		   	
	     	   }
	        });
    }
	
	public String getSetting(String key) {
        ShareRef = getSharedPreferences(STRING_NAME_USERSETTING, Context.MODE_WORLD_WRITEABLE);
        return ShareRef.getString(key, "");
	}
	public void doinBackGround()
	{
		try {
			 //lấy cursor của music
		        myCursor=this.managedQuery(android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, null, null, null, null);
		        startManagingCursor(myCursor);
		        while (myCursor.moveToNext())
		        {
		        	String id=myCursor.getString(myCursor.getColumnIndexOrThrow(Audio.Media._ID));
		            String musicName = myCursor.getString(myCursor.getColumnIndexOrThrow(Audio.Media.DISPLAY_NAME));
//		            int musicSize= myCursor.getInt(myCursor.getColumnIndexOrThrow(Audio.Media.SIZE));
		            String Size=myCursor.getString(myCursor.getColumnIndexOrThrow(Audio.Media.SIZE));
//		
		    		Size= getFileSize(Size);
		    	//	System.out.println(Size);
		            String musicPath=myCursor.getString(myCursor.getColumnIndexOrThrow(Audio.Media.DATA));
		            listMusic.add(new myMusic(id,musicName, Size,musicPath));
		        }
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
     	
	}

	public class BackGround extends AsyncTask<Void, Void, Void>
	{
		
		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			super.onPreExecute();
			listMusic.clear();
			loadingMusicDialog.show();
		}
		@Override
		protected Void doInBackground(Void... params) {
			// TODO Auto-generated method stub
			 try {
                 Thread.sleep(1000);
               doinBackGround();

         } catch (Exception e) {
                 // TODO Auto-generated catch block
                 e.printStackTrace();
         }
			return null;
		}
		@Override
		protected void onPostExecute(Void result) {
			// TODO Auto-generated method stub
			loadingMusicDialog.dismiss();
			mAdapter= new MusicListAdapter(context,listMusic);
			listview.setAdapter(mAdapter);
			
	        myCursor.close();
	        
			super.onPostExecute(result);
		}
		
		
	}
	 
	//-------------------------------xu lý menu---------------------------
	public boolean onCreateOptionsMenu(Menu menu) 
	 {
	    	// TODO Auto-generated method stub
		new MenuInflater(context).inflate(R.menu.backup_file_option_menu, menu);
	    return super.onCreateOptionsMenu(menu);
	 }
   // bat su kien nhan menu item chon tat ca hoac ba chon tat ca
	@Override
	public boolean onMenuOpened(int featureId, Menu menu) 
	{
	   // TODO Auto-generated method stub
	   if(numberOfItemSelected==listMusic.size())
	   {
		   menu.findItem(R.id.menu_fileSelectAll).setTitle(getResources().getString(R.string.txt_uncheckall));
	   }
	   else
	   {
		   menu.findItem(R.id.menu_fileSelectAll).setTitle(getResources().getString(R.string.txt_checkall));
		      
	   }
	return super.onMenuOpened(featureId, menu);
   }

	    @Override
	public boolean onOptionsItemSelected(MenuItem item) 
	 {
	    	// TODO Auto-generated method stub
	    switch(item.getItemId())
	    {
	    	case R.id.menu_fileBackup:
	    		
	    			// xu ly chon file check
    				//neu flag =1 thì đã có sms check roi 
    				//flag=0 nghia là chưa có chon sms nao
    				int flag=0;
    				for(int i=0;i<listMusic.size();i++)
    				{
    					if(listMusic.get(i).getChecked()==true)
    					{
    					flag=1;
    					numberOfItemSelected++;
    					System.out.println("size"+listMusic.get(i).getSize());
    					System.out.println("maxsize"+maxSize);
    					maxSize=Double.valueOf(listMusic.get(i).getSize());
    					System.out.println("maxsize2"+maxSize);
    					}	
    				}
    				if(flag==0)
    				{
    					numberOfItemSelected=0;
    				}
	    			//xu ly backup
    				if(listMusic.isEmpty())
    				{
    					showToast("Không có danh sách");
    				}
    				else
    				{
    					if (numberOfItemSelected==0) 
    					{
    						showToast("Vui lòng chọn tập tin cần sao lưu!");
						}
    					else
    					{
    						showConfirmDialog(getResources().getString(R.string.dialog_thongbao), getResources().getString(R.string.dialog_message_server), new OnClickListener() 
    						{
								
								@Override
								public void onClick(DialogInterface dialog, int which) 
								{
									//check ketnoi internet 
								
									CheckInternet chkI= new CheckInternet(context);
									if (maxSize>=5)
									{
										System.out.print(maxSize);
										showAlertDialog("Thông báo","Vượt quá dung luợng cho phép , bạn chỉ được sao lưu tối đa 5 MB 1 lần ", new OnClickListener() {
											
											@Override
											public void onClick(DialogInterface dialog, int which) {
												// TODO Auto-generated method stub
												
												dialog.dismiss();
											}
										});
										maxSize=0.;
									}
									else if(chkI.checkStatus().equals(true))
										{
										 	new BackupServerTask().execute();								        	
										}
								     else{
								        	Log.d("ketnoi", "ko co ket noi internet");
								        	showToast("Không có kết nối ");
								        
								        }
									
								}
							});
    					}
    				}

	    			return true;
	    	case R.id.menu_fileLogout:
	    			logOut();
	    			Intent intent = new Intent(MusicActivity.this, LoginActivity.class);
	    			startActivity(intent);
	    			this.finish();
	    			return true;
	    	
	    	case R.id.menu_fileSelectAll:
	    			//xu ly check all
	    			if(numberOfItemSelected==listMusic.size())
	    			{
	    				// xu ly bo chon
	    				for(int i=0;i<listMusic.size();i++)
	    				{
	    					listMusic.get(i).setChecked(false);
	    				
	    				}
	    				numberOfItemSelected=0;
	    			}
	    			else
	    			{
	    				// xu ly chon
	    				for(int i=0;i<listMusic.size();i++)
	    				{	
	    					listMusic.get(i).setChecked(true);
	    				}
	    				numberOfItemSelected=listMusic.size();
	    			}
	    				mAdapter.notifyDataSetChanged();
	    				return true;
	    			}
	    return false;
	    }
	//------------------- cac ham xu ly khac ----------------------------------------
public class BackupServerTask extends AsyncTask<Void, Void, Void>
{
	@Override
	protected void onPreExecute() {
		// TODO Auto-generated method stub
		super.onPreExecute();
		loadingMusicDialog.setMessage(getResources().getString(R.string.dialog_message_progress_up_server));
		loadingMusicDialog.show();
	}
	
	@Override
	protected Void doInBackground(Void... params) 
	{
		// TODO Auto-generated method stub
		try {
			for(int i=0;i<listMusic.size();i++)
			{
				if(listMusic.get(i).getChecked()==true)
				{
					myMusic entry =listMusic.get(i);
					itemMusicCheck.add(entry);
				}
			}
			backupMusicToServer(itemMusicCheck);


		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		return null;
	}
	@Override
	protected void onPostExecute(Void result) 
	{
		// TODO Auto-generated method stub
		loadingMusicDialog.dismiss();	
//		duyet mang và set check lai false
		for(int i=0;i<listMusic.size();i++)
		{
			listMusic.get(i).setChecked(false);
		}
		mAdapter.notifyDataSetChanged();
		showAlertDialog(getResources().getString(R.string.dialog_thongbao), getResources().getString(R.string.dialog_message_saoluuthanhcong), new OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				// TODO Auto-generated method stub
				dialog.dismiss();
			}
		});
		super.onPostExecute(result);
	}
}
public void  backupMusicToServer(ArrayList<myMusic> itemCheck) 
	{
		try 
		{
			for(int i=0 ; i<itemCheck.size();i++)
			{			
					File file= new File(itemCheck.get(i).getPath());
					FileInputStream fis = new FileInputStream(file);
					String temp = String.valueOf(userid)+"@"+String.valueOf(filetype)+"@"+"sao luu tap tin nhac len may chu!";
//					// xu ly ma hoa du lieu 
					String output = itemCheck.get(i).getPath()+".aes";
					Log.d("output",output);
					Log.d("output",file.getPath());
					aes= new AESControl(username);
					aes.EncFile(file.getPath(), output);
					
					FileInputStream fis1= new FileInputStream(output);
					File encryptFile= new File(output);
					httpUploader up= new httpUploader(urlString, temp,itemCheck.get(i).getName());
					System.out.println(up.doStart(fis1));
					encryptFile.delete();
					
				
			}
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
	}

	@Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
    	// TODO Auto-generated method stub
    	if(keyCode==KeyEvent.KEYCODE_BACK && event.getRepeatCount()==0){
//    		finish();
    	}
    	return super.onKeyDown(keyCode, event);
    }



	
}

